//
//  HJComposeViewController.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/30.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

class HJComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        prepareUI()
        // 监听键盘的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    private func prepareUI() {
        setupNavigationBar()
        setupTextView()
        setupToolBar()
    }
    
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
        setupTitleView()
    }
    private func setupTitleView() {
        let prefix = "发微博"
        if let name = HJUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            let text = prefix + "\n" + name
            let label = UILabel()
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(13)
            label.textAlignment = NSTextAlignment.Center
            label.numberOfLines = 0
            let attr = NSMutableAttributedString(string: text)
            let nameRange = (text as NSString).rangeOfString(name)
            attr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(),
                                NSFontAttributeName: UIFont.systemFontOfSize(12)],
                                range: nameRange)
            label.attributedText = attr
            label.sizeToFit()
            navigationItem.titleView = label
        }else {
            navigationItem.title = prefix
        }
        
    }
    private func setupToolBar() {
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_add_background", "action": "add"]]
        
        toolBar.items = [UIBarButtonItem]()
        var index = 0
        for dict in itemSettings {
            let imageName = dict["imageName"]!
            let action = dict["action"]!
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action))
            toolBar.items?.append(item)
            let button = item.customView
            button?.tag = index
            index++
            // 在每个按钮之间添加弹簧将其隔开
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 最后一个不需要弹簧，将其移除
        toolBar.items?.removeLast()
    }
    private func setupTextView() {
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    
    // MARK: - 键盘frame将要改变
    func keyboardWillChangeFrame(notification: NSNotification) {
        let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        let newFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue ?? CGRectZero
        let margin = -(UIScreen.height - newFrame.origin.y)
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(margin)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - Button click event
    @objc private func dismiss() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send() {
        HJPrint(msg: "发送微博")
    }
    @objc private func picture() {
        HJPrint(msg: "picture")
    }
    @objc private func trend() {
        HJPrint(msg: "trend")
    }
    @objc private func mention() {
        HJPrint(msg: "mention")
    }
    @objc private func emoticon() {
        HJPrint(msg: "emoticon")
    }
    @objc private func add() {
        HJPrint(msg: "add")
    }
    
    
    // MARK: - Lazy load
    private lazy var toolBar: UIToolbar = {
        let toolBar = UIToolbar()
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        return toolBar
    }()
    private lazy var textView: HJPlaceholderTextView = {
       let textView = HJPlaceholderTextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.blackColor()
        textView.backgroundColor = UIColor.brownColor()
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.delegate = self
        textView.placeholder = "分享新鲜事..."
        return textView
    }()
}

// MARK: - UITextViewDelegate
extension HJComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
